<template>
  <div class="update-photo">
    <img class="img" :src="img" ref="img" />

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { updateUserPhoto } from "@/api/User";
export default {
  name: "UpdatePhoto",
  components: {},
  props: {
    // 预览图片地址信息
    img: {
      type: [String, Object],
      required: true,
    },
  },
  data() {
    return {};
  },
  mounted() {
    // mounted里面，注意：因为在这里才可以使用真实的DOM节点
    // new Cropper(图片节点,配置项)
    this.cropper = new Cropper(this.$refs.img, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
    });
  },
  methods: {
    // 确定事件
    onConfirm() {
      // 确定按钮点击之后才可以做裁剪功能
      //    this.cropper.getCroppedCanvas().toBlob(blob=>{   blob就是文件信息 })
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        let fd = new FormData();
        fd.append("photo", blob);
        let { data } = await updateUserPhoto(fd);
        this.$emit("updatePhoto", data.data.photo);
        this.$emit("close");
      });
    },
  },
};
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
